<template>
  <div class="menu-management-container">
    <el-row :gutter="20">
      <el-col :lg="4" :md="8" :sm="24" :xl="4" :xs="24">
        <vab-card shadow="hover">
          <el-tree
            :data="data"
            :default-expanded-keys="expandDefault"
            highlight-current
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
          />
        </vab-card>
      </el-col>
      <el-col :lg="20" :md="16" :sm="24" :xl="20" :xs="24">
        <vab-card shadow="hover">
          <vab-query-form>
            <vab-query-form-top-panel :span="12">
              <el-form inline :model="queryForm" @submit.prevent>
                <el-form-item>
                  <el-input
                    v-model.trim="queryForm.search"
                    clearable
                    :placeholder="translate('请输入名称')"
                    @keyup.enter="fetchData('search')"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    :icon="Search"
                    type="primary"
                    @click="fetchData('search')"
                  >
                    {{ translate('查询') }}
                  </el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-top-panel>
          </vab-query-form>
          <div class="add">
            <el-button
                v-if="MenuAuth('add')"
                :icon="Plus"
                type="primary"
                @click="handleEdit()"
                plain
              >
                {{ translate('添加') }}
              </el-button>
          </div>
          <el-table
            v-loading="listLoading"
            border
            :data="list"
            default-expand-all
            lazy
            row-key="CompanyId"
            :tree-props="{ children: 'Contact' }"
          >
            <el-table-column
              :label="translate('物资编码')"
              prop="Code"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('物料名称')"
              prop="FullName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('物资简称')"
              prop="Abbreviation"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('规格型号')"
              prop="Spec"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('计量单位')"
              prop="Unit"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('单价')"
              prop="Price"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('标准')"
              prop="Standard"
              show-overflow-tooltip
            />
            <el-table-column
              :label="translate('备注')"
              prop="Remark"
              show-overflow-tooltip
            />
            <!-- <el-table-column
              label="供应商"
              prop="SuppCodes"
              show-overflow-tooltip
            />
            <el-table-column
              label="创建人"
              prop="CreateUserName"
              show-overflow-tooltip
            />
            <el-table-column
              label="创建时间"
              prop="CreateDate"
              show-overflow-tooltip
            /> -->
            <el-table-column
              :label="translate('操作')"
              show-overflow-tooltip
              width="240"
            >
              <template #default="{ row }">
                <!-- <el-button text type="primary" @click="handleEdit(row, 'edit')">
                  编辑
                </el-button> -->
                <el-button
                  v-if="MenuAuth('delete')"
                  size="small"
                  type="danger"
                  @click="handleDelete(row)"
                  plain
                >
                  {{ translate('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <template #empty>
              <!-- <el-image
                class="vab-data-empty"
                :src="require('@/assets/empty_images/data_empty.png')"
              /> -->
              <el-empty
                class="vab-data-empty"
                :description="translate('暂无数据')"
              />
            </template>
          </el-table>
          <el-pagination
            background
            :current-page="queryForm.pageNo"
            :layout="layout"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>
    <edit ref="editRef" :tree="data" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { doDelete, getSupplierList, getPageData } from '@/api/supItem'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import { useSettingsStore } from '@/store/modules/settings'
  import { MenuAuth } from '~/src/utils/permission'
  import { translate } from '@/i18n'
  export default defineComponent({
    name: 'SupItem',
    components: {
      Edit: defineAsyncComponent(() => import('./components/supItemEdit')),
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        editRef: null,
        data: [],
        defaultProps: {
          children: 'ChildNodes',
          label: 'text',
        },
        list: [],
        tree: [],
        queryForm: {
          companyId: 'string',
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"ModuleId","value":"value","displayType":"equal"}]`,
          export: false,
          search: '',
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        listLoading: true,
        expandDefault: [],
      })
      //列表编辑
      const handleEdit = (row, type) => {
        if (row && row.SIID) {
          state['editRef'].showEdit(row, type)
        } else {
          // if (!row) state.queryForm.userId = 0
          state['editRef'].showEdit(state.queryForm, type)
        }
      }
      //页面刷新
      const settingsStore = useSettingsStore()
      const { theme } = storeToRefs(settingsStore)
      const $pub = inject('$pub')
      const refreshRoute = () => {
        $pub('reload-router-view')
      }
      //列表删除
      const handleDelete = (row) => {
        if (row.IID) {
          $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
            const { message } = await doDelete({ siid: row.SIID })
            //删除列表默认回到第一页
            $baseMessage(message, 'success', 'vab-hey-message-success')
            // refreshRoute()
            fetchData('search')
          })
        }
      }
      //菜单表格
      const fetchData = async (val) => {
        //wheres重新赋值
        const params = JSON.parse(JSON.stringify(state.queryForm))
        //搜索
        if (val == 'search') {
          params.pageNo = 1
          params.wheres = `[{"name":"FullName","value":"${params.search}","displayType":"like"},{"name":"SupID","value":"${params.moduleId}","displayType":"equal"}]`
        } else {
          params.wheres = `[{"name":"SupID","value":"${params.moduleId}","displayType":"equal"}]`
        }
        state.listLoading = true
        const data = await getPageData(params)
        state.list = data?.data?.rows
        state.total = data?.data?.total
        state.listLoading = false
      }
      // //树形数据点击
      const handleNodeClick = (data) => {
        //树形点击结构判断
        if (data.ChildNodes && data.ChildNodes.length > 1) {
          state.queryForm.moduleType = 'ParentId'
        } else {
          state.queryForm.moduleType = 'ModuleId'
        }
        state.queryForm.moduleId = data.id
        state.queryForm.companyId = data.id
        fetchData()
      }
      //分页条数切换
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      //分页切换
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      //获取树形结构下第一个ID
      const getFirstNode = (tree) => {
        if (tree && tree.ChildNodes.length > 0) {
          getFirstNode(tree.ChildNodes[0])
        } else if (tree) {
          state.queryForm.moduleId = tree.id
          state.expandDefault.push(state.queryForm.moduleId)
          return
        }
      }
      //树形结构数据
      getSupplierList({}).then(({ data }) => {
        const list = data.data
        state.data = JSON.parse(list)
        //默认选中第一个
        getFirstNode(state.data[0])
        state.expandDefault.push(state.queryForm.moduleId)
        fetchData()
      })
      // onMounted(() => {
      //   getTree()
      // })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        Delete,
        Plus,
        Search,
        getFirstNode,
        handleCurrentChange,
        handleSizeChange,
        refreshRoute,
        MenuAuth,
        translate,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.menu-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
</style>
